﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using THSERP.BaseProvider;
using THSLib;
using THSERP.BusinessEntities;
using System.Transactions;
namespace THSERP.Modules.POS
{
    public partial class guiSeperatedCombinePOS : THSERPScreen
    {
       // DataSet dsBRPOS = null;
        protected int _qtySeperate;
        protected String _descSeperate = String.Empty;
        public int QtySeperate
        {
            get { return _qtySeperate; }
            set { _qtySeperate = value; }
        }
        public String DescSeparete
        {
            get { return _descSeperate; }
            set { _descSeperate = value; }
        }
        protected int _orgPOSID;
        protected int _newPOSID;
        protected THSList<POSItemsEntity> lstNewItems;
        BRPOSItemsController objBRPOSItemsController = new BRPOSItemsController();
        ICProductsController objICProductsController = new ICProductsController();
        BRPOSLocationsController objBRPOSLocationsController = new BRPOSLocationsController();
        public THSList<POSItemsEntity> NewItemsList
        {
            get { return lstNewItems; }
            set { lstNewItems = value; }
        }
        public int OrgPOS
        {
            get { return _orgPOSID; }
            set { _orgPOSID = value; }
        }
       
        public int NewPOS
        {
            get { return _newPOSID; }
            set { _newPOSID = value; }
        }
        BRPOSsController objBRPOSsController = new BRPOSsController();
        public guiSeperatedCombinePOS()
        {
            
            InitializeComponent();


        }
        public guiSeperatedCombinePOS( int orgPOS)
        {
            
            this.OrgPOS = orgPOS;
            InitializeComponent();
         
            
        }

        private void guiSeperatedCombinePOS_Load(object sender, EventArgs e)
        {
            
            lstNewItems = new THSList<POSItemsEntity>();
            POSEntities entity =(POSEntities)((BaseModuleERP)Module).CurrentModuleEntity;
            ths_rpsProductIDOrg.DataSource = InitialProductReponsitory();
            ths_rpsPOSIDOrg.DataSource = InitialPOSReponsitory();
            ths_rpsProductIDNew.DataSource = InitialProductReponsitory();
            fld_dgcPOSItems.DataSource =entity.BRPOSItemsList;
            fld_dgvPOSItems.ExpandAllGroups();
            
            
        }
        private List<ICProductsInfo> InitialProductReponsitory()
        {
            DataSet ds = new ICProductsController().GetAllObjects();
            List<ICProductsInfo> lstProducts =new List<ICProductsInfo>();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                ICProductsInfo obj = (ICProductsInfo)new ICProductsController().GetObjectFromDataRow(row);
                if (obj.ICProductTypeCombo.Equals(POSModule.cstProductTypeItem) || obj.ICProductTypeCombo.Equals(POSModule.cstProductTypeGoods) || obj.ICProductTypeCombo.Equals(POSModule.cstProductTypeFinished))
                    lstProducts.Add(obj);

            }
            return lstProducts;
        }
        public DataTable InitialPOSReponsitory()
        {
            String mainTableName=THSUtil.GetTableNameFromBusinessObjectType(typeof(BRPOSsInfo));
            THSApp.InitDataToLookupTable(mainTableName);
             DataTable dtLookupTable = new DataTable();
            if (THSApp.LookupTables[mainTableName] != null)
                dtLookupTable = ((DataSet)THSApp.LookupTables[mainTableName]).Tables[0].Copy();
            return dtLookupTable;
        }

        private void fld_trlGELocations_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            if (e.Node.HasChildren)
                NewPOS = 0;
            else
                NewPOS = Convert.ToInt32(e.Node["GELocationID"].ToString());
        }

        private void fld_btnClose_Click(object sender, EventArgs e)
        {
            ((POSModule)Module).ActionCancel();
            this.Close();
        }

      

        private void fld_btnBackward_Click(object sender, EventArgs e)
        {
            int iRowhandle = fld_dgvPOSItemNew.FocusedRowHandle;
            if (iRowhandle >= 0)
            {
                POSEntities entity = (POSEntities)((BaseModuleERP)Module).CurrentModuleEntity;
                POSItemsEntity itemEntity=(POSItemsEntity)fld_dgvPOSItemNew.GetRow(iRowhandle);
                lstNewItems.RemoveAt(iRowhandle);
                fld_dgcPOSItemNew.DataSource = lstNewItems;
                fld_dgcPOSItemNew.RefreshDataSource();
                fld_dgvPOSItemNew.RefreshData();
                //
                itemEntity.FK_BRPOSID = OrgPOS;
                entity.BRPOSItemsList.Add(itemEntity);
                entity.UpdateModuleObjectBindingSource("BRPOSItems");
                entity.InvalidateModuleObjects(OrgPOS);
                fld_dgcPOSItems.DataSource = entity.BRPOSItemsList;
                fld_dgcPOSItems.RefreshDataSource();
                fld_dgvPOSItems.RefreshData();
            }
            fld_dgvPOSItemNew.ExpandAllGroups();
            fld_dgvPOSItems.ExpandAllGroups();
        }

        private void fld_btnForward_Click_1(object sender, EventArgs e)
        {
            QtySeperate = Convert.ToInt32(fld_Qty.Value);
            int iRowhandle = fld_dgvPOSItems.FocusedRowHandle;  
            if (iRowhandle >= 0)
            {
                POSEntities entity = (POSEntities)((BaseModuleERP)Module).CurrentModuleEntity;
                BRPOSItemsInfo objBRPOSItemsInfo = (BRPOSItemsInfo)entity.ModuleObjects[POSEntities.strBRPOSItemsObjectName];
                POSItemsEntity itemEntity = (POSItemsEntity)fld_dgvPOSItems.GetRow(iRowhandle);
               // BRPOSItemsInfo objBRPOSItemsInfo = (BRPOSItemsInfo)itemEntity.SetToBusinessObject(POSEntities.strBRPOSItemsObjectName);
                if (fld_Qty.Value == 0 || fld_Qty.Value < 0)
                {
                    MessageBox.Show("Chọn số lượng món chuyển Bill!", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            
          
                if (QtySeperate > itemEntity.BRPOSItemProductQty)
                {
                    MessageBox.Show("Số lượng món chuyển không được lớn hơn số lượng hiện có!", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (fld_dgvPOSItems.RowCount <= 2 && itemEntity.BRPOSItemProductQty== 1)
                 {
                    MessageBox.Show("Không cho phép chuyển Bill chỉ còn 1 món!","Cảnh báo",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                     return;
                    }
                    
                
                if (QtySeperate == itemEntity.BRPOSItemProductQty)
                {
                    if (NewItemsList.Exists("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID))
                    {
                        
                        int iIndex = NewItemsList.PosOf("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID);
                        ((POSItemsEntity)NewItemsList[NewItemsList.PosOf("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID)]).BRPOSItemProductQty += QtySeperate;
                        ((POSItemsEntity)NewItemsList[NewItemsList.PosOf("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID)]).BRPOSItemProductQtyOld = ((POSItemsEntity)NewItemsList[NewItemsList.PosOf("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID)]).BRPOSItemProductQty;

                        ((POSItemsEntity)NewItemsList[NewItemsList.PosOf("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID)]).BRPOSItemQty1 = ((POSItemsEntity)NewItemsList[NewItemsList.PosOf("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID)]).BRPOSItemProductQty;
                        ((POSItemsEntity)NewItemsList[NewItemsList.PosOf("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID)]).BRPOSItemTotalAmount =
                            ((POSItemsEntity)NewItemsList[NewItemsList.PosOf("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID)]).BRPOSItemProductUnitPrice *
                            ((POSItemsEntity)NewItemsList[NewItemsList.PosOf("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID)]).BRPOSItemProductQty;
                        entity.SetProductPrice(NewItemsList[iIndex], THSUtil.GetTableNameFromBusinessObjectType(typeof(BRPOSItemsInfo)));
                    }
                    else
                    {
                        lstNewItems.Add(itemEntity);
                    }
                    itemEntity.FK_BRPOSID = 0;
                    fld_dgcPOSItemNew.DataSource = NewItemsList;
                    fld_dgcPOSItemNew.RefreshDataSource();
                    fld_dgvPOSItemNew.RefreshData();
                    //get object to remove

                    entity.BRPOSItemsList.RemoveSelectedRowObjectFromList(); ;
                    entity.BRPOSItemsList.GridView.RefreshData();
                    fld_dgcPOSItems.DataSource = entity.BRPOSItemsList;
                    fld_dgcPOSItems.RefreshDataSource();
                    fld_dgvPOSItems.RefreshData();
                }
                else
                {
                    //this of grid
                    objBRPOSItemsInfo.BRPOSItemProductQty = objBRPOSItemsInfo.BRPOSItemProductQty - QtySeperate;
                    objBRPOSItemsInfo.BRPOSItemProductQtyOld = objBRPOSItemsInfo.BRPOSItemProductQty;
                    objBRPOSItemsInfo.BRPOSItemQty1 = objBRPOSItemsInfo.BRPOSItemProductQty;
                    entity.SetProductPriceByProductUnitPrice();
                    entity.SetValuesAfterValidateProductQty();
                    entity.BRPOSItemsList.ChangeObjectFromList();
                    entity.UpdateModuleObjectBindingSource(POSEntities.strBRPOSItemsObjectName);
                    entity.UpdateTotalAmount();

                    if (NewItemsList.Exists("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID))
                    {
                        ((POSItemsEntity)NewItemsList[NewItemsList.PosOf("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID)]).BRPOSItemProductQty += QtySeperate;
                        ((POSItemsEntity)NewItemsList[NewItemsList.PosOf("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID)]).BRPOSItemProductQtyOld = ((POSItemsEntity)NewItemsList[NewItemsList.PosOf("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID)]).BRPOSItemProductQty;
                      
                        ((POSItemsEntity)NewItemsList[NewItemsList.PosOf("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID)]).BRPOSItemQty1 = ((POSItemsEntity)NewItemsList[NewItemsList.PosOf("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID)]).BRPOSItemProductQty;
                        ((POSItemsEntity)NewItemsList[NewItemsList.PosOf("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID)]).BRPOSItemTotalAmount =
                            ((POSItemsEntity)NewItemsList[NewItemsList.PosOf("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID)]).BRPOSItemProductUnitPrice *
                            ((POSItemsEntity)NewItemsList[NewItemsList.PosOf("FK_ICProductID", objBRPOSItemsInfo.FK_ICProductID)]).BRPOSItemProductQty;
                    }
                    else
                    {
                        BRPOSItemsInfo objNewOjbject = new BRPOSItemsInfo();
                        POSItemsEntity newItemEntity = new POSItemsEntity();
                        THSUtil.CopyObjectItems(objBRPOSItemsInfo, objNewOjbject, THSUtil.GetTableNameFromBusinessObjectType(typeof(BRPOSItemsInfo)));
                        objNewOjbject.BRPOSItemProductQty = QtySeperate;
                        objNewOjbject.BRPOSItemQty1 = QtySeperate;
                        objNewOjbject.BRPOSItemProductQtyOld = objNewOjbject.BRPOSItemProductQty;
                        //objNewOjbject.BRPOSItemTotalAmount = objNewOjbject.BRPOSItemProductUnitPrice * objNewOjbject.BRPOSItemProductQty;
                        entity.SetProductPrice(objNewOjbject);
                        objNewOjbject.BRPOSItemProductDesc = DescSeparete;
                        newItemEntity.GetFromBusinessObject(objNewOjbject);
                        lstNewItems.Add(newItemEntity);
                    }
                    fld_dgcPOSItemNew.DataSource = NewItemsList;
                    fld_dgcPOSItemNew.RefreshDataSource();
                    fld_dgvPOSItemNew.RefreshData();
                    //
                    fld_dgcPOSItems.DataSource = entity.BRPOSItemsList;
                    fld_dgcPOSItems.RefreshDataSource();
                    fld_dgvPOSItems.RefreshData();
                    
                }
            }
            fld_dgvPOSItems.ExpandAllGroups();
            fld_dgvPOSItemNew.ExpandAllGroups();
        }

        private void fld_btnOK_Click(object sender, EventArgs e)
        {
            if (NewItemsList.Count == 0)
            {
                MessageBox.Show("Chưa chọn món để tách Bill!", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
           using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
           {
                try
                {
                    //double totalAmount = 0;
                    // double  BRPOSNetAmount = 0;
                    //double BRPOSTaxAmount = 0;
                    //double BRPOSSubTotalAmount = 0;
                    
                    POSEntities entity = (POSEntities)((BaseModuleERP)Module).CurrentModuleEntity;
                    BRPOSsInfo objMainOjbect = (BRPOSsInfo)((BaseModuleERP)Module).CurrentModuleEntity.MainObject;
                    BRPOSsInfo objBRPOSsInfo = new BRPOSsInfo();
                    THSUtil.CopyMainObjects(objMainOjbect, objBRPOSsInfo);
                    objBRPOSsInfo.AACreatedUser = THSApp.CurrentUser;
                    objBRPOSsInfo.AAIsPrinted = false;
                    //get first location name
                    String locationName=String.Empty;
                    if (entity.BRPOSLocationList.Count > 0)
                    {
                        GELocationsInfo objGELocationsInfo =(GELocationsInfo)new GELocationsController().GetObjectByID(((BRPOSLocationsInfo)entity.BRPOSLocationList[0]).FK_GELocationID);
                        if(objGELocationsInfo!=null)
                            locationName=objGELocationsInfo.GELocationName;
                    }
                    objBRPOSsInfo.BRPOSNo = GetMainObjectNo("POS", locationName);

                    objBRPOSsInfo.BRPOSWorkingShiftName = THSApp.CurrentWorkingShift.HRShiftName;
                    objBRPOSsInfo.FK_HREmployeeID = THSApp.CurrentUsersInfo.FK_HREmployeeID;
                    objBRPOSsInfo.BRPOSDate = THSApp.WorkingDate;
                    objBRPOSsInfo.BRPOSDesc = "Bill tách ra từ mã số: "+objMainOjbect.BRPOSNo;
                    List<BRPOSItemsInfo> itemList= CalculateTotalAmount(NewItemsList, objBRPOSsInfo);
                    int iNewPOSID = objBRPOSsController.CreateObject(objBRPOSsInfo);
                    THSApp.UpdateObjectNumbering("POS");
                    //create item
                    if (iNewPOSID > 0)
                    {

                        foreach (BRPOSItemsInfo objBRPOSItemsInfo in itemList)
                        {
                            objBRPOSItemsInfo.FK_BRPOSID = iNewPOSID;
                            objBRPOSItemsController.CreateObject(objBRPOSItemsInfo);

                        }
                        //chage Bill locattion
                        foreach (BRPOSLocationsInfo objBRPOSLocationsInfo in entity.BRPOSLocationList)
                        {
                                BRPOSLocationsInfo newObject = new BRPOSLocationsInfo();
                                newObject.FK_BRPOSID = iNewPOSID;
                                newObject.FK_GELocationID = objBRPOSLocationsInfo.FK_GELocationID;
                                objBRPOSLocationsController.CreateObject(newObject);
                        }
                        ((POSModule)Module).IsSeperated = true;
                        ((POSModule)Module).ActionSaveSeparateCombine();
                    }

                    MessageBox.Show("Tách Bill thành công!", "THS Say: Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                    ((POSModule)Module).Search();
                    scope.Complete();
                }
                catch (Exception)
                {
                    scope.Dispose();
                    MessageBox.Show("Đã có lỗi xẩy ra. Vui lòng kiểm tra lại.","THS Say:Lỗi",MessageBoxButtons.OK,MessageBoxIcon.Error);
                }
            }
        }

        private void guiSeperatedCombinePOS_FormClosing(object sender, FormClosingEventArgs e)
        {
            ((POSModule)Module).ActionCancel();
        }
        private string GetMainObjectNo(string ModeleName,String formatNo)
        {
            String strMainObjectNo = String.Empty;
            GENumberingController objGENumberingController = new GENumberingController();
            GELocationsController objGELocationsController = new GELocationsController();
            GENumberingInfo objGENumberingInfo = (GENumberingInfo)new GENumberingController().GetObjectByName(ModeleName);
            if (objGENumberingInfo != null)
            {
                strMainObjectNo = String.Format("{0}/{1}{2}", formatNo, objGENumberingInfo.GENumberingPrefix, objGENumberingInfo.GENumberingStart);
            }
            return strMainObjectNo;
            //return base.GetMainObjectNo();
        }
        //calculatotal amoutn new object
        private List<BRPOSItemsInfo> CalculateTotalAmount(List<POSItemsEntity> entitList, BRPOSsInfo objPOSsInfo)
        {
         
            objPOSsInfo.BRPOSNetAmount = 0;
            objPOSsInfo.BRPOSTaxAmount = 0;
            objPOSsInfo.BRPOSSubTotalAmount = 0;
            List<BRPOSItemsInfo> itemList = new List<BRPOSItemsInfo>();
            foreach (POSItemsEntity itemEntity in entitList)
            {
                objPOSsInfo.BRPOSNetAmount += itemEntity.BRPOSItemNetAmount;
                objPOSsInfo.BRPOSTaxAmount += itemEntity.BRPOSItemTaxAmount;
                objPOSsInfo.BRPOSSubTotalAmount += itemEntity.BRPOSItemTotalAmount;
                BRPOSItemsInfo objBRPOSItemsInfo = (BRPOSItemsInfo)itemEntity.SetToBusinessObject("BRPOSItems");
                itemList.Add(objBRPOSItemsInfo);
            }
            objPOSsInfo.BRPOSDiscountAmount = objPOSsInfo.BRPOSSubTotalAmount * objPOSsInfo.BRPOSDiscountPerCent / 100;
            objPOSsInfo.BRPOSTotalAmount = objPOSsInfo.BRPOSSubTotalAmount - objPOSsInfo.BRPOSDiscountAmount;
            return itemList;
        }
        private void fld_dgvPOSItems_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            int iRowhandle =fld_dgvPOSItems.FocusedRowHandle;
            if(iRowhandle>=0)
            {
                POSItemsEntity itemEntiy = (POSItemsEntity)fld_dgvPOSItems.GetRow(e.FocusedRowHandle);
                fld_Qty.Value = Convert.ToDecimal(itemEntiy.BRPOSItemProductQty);
                POSEntities entity = (POSEntities)((BaseModuleERP)this.Module).CurrentModuleEntity;
                entity.BRPOSItemsList.GridView.FocusedRowHandle = e.FocusedRowHandle;
            }
        }

        private void fld_dgvPOSItems_Click(object sender, EventArgs e)
        {
            int iRowhandle = fld_dgvPOSItems.FocusedRowHandle;
            if (iRowhandle >= 0)
            {
                POSItemsEntity itemEntiy = (POSItemsEntity)fld_dgvPOSItems.GetRow(iRowhandle);
                fld_Qty.Value = Convert.ToDecimal(itemEntiy.BRPOSItemProductQty);
                POSEntities entity = (POSEntities)((BaseModuleERP)this.Module).CurrentModuleEntity;
                entity.BRPOSItemsList.GridView.FocusedRowHandle = iRowhandle;
            }
        }
       
    }
}